/*
	网站页面控制器
*/
var AV 				= require('leanengine');
var moment		= require('moment');
var fs 				= require('fs');
var xml2js 		= require('xml2js');
var request 	= require('request');
var qr 				= require('qr-image');
var mdCommon	= require('../modules/common');
var mdWX			= require('../modules/weixin.js');
var mdAlipay	= require('../modules/alipay.js');
var avBrand 			= AV.Object.extend("Brand");
var avCart 				= AV.Object.extend("Cart");
var avImage 			= AV.Object.extend("Image");
var avItem 				= AV.Object.extend("item");
var avOrderList 	= AV.Object.extend("OrderList");
var avSysConfig 	= AV.Object.extend("SysConfig");

/**
 * 网站首页
 * 2015.04.25  by 胡斌
 */
exports.homePage = function(req,res) {
	//res.redirect('/admin-login');
	var querySysConfig 	= new AV.Query(avSysConfig);
	querySysConfig.equalTo("type","homepage");
	querySysConfig.find().then(function(results) {
		var slides,catagory;
		for(var i=0;i<results.length;i++){
			if(results[i].get("name")=="home_banner"){
				slides=eval("("+results[i].get('value')+")");
			}else if(results[i].get("name")=="home_catagory"){
				catagory=eval("("+results[i].get('value')+")");
			}
		}
		res.render('main/index.html',{
			user:req.AV.user,
			slides:slides,
			catagory:catagory
		});
	},function(error){
		console.dir(error);
		mdCommon.sentErr(res,req,error);
	});/**/
}

exports.loginPage = function(req,res) {
	if(req.AV.user){
		if(req.query.refer){
			res.redirect(decodeURI(req.query.refer));
		}else{
			res.redirect('/');
		}
	}else{
		res.render('main/login.html',{
			user:req.AV.user,
			refer:req.query.refer,
			error:req.query.error
		});
	}
}

exports.registerPage = function(req,res) {
	var error=req.query.error;
	if(req.AV.user){
		req.currentUser.logOut();
	  res.clearCurrentUser(); // 从 Cookie 中删除用户
	}
	res.render('main/register.html',{
		error:error,
		refer:req.query.refer,
		user:false
	});
}

/**
 * 后台登录页面
 * 2015.04.18  by 胡斌
 */
exports.logoutPage = function(req,res) {
	req.currentUser.logOut();
  res.clearCurrentUser(); // 从 Cookie 中删除用户
	if(req.query.refer){
	  res.redirect('/login?refer='+req.query.refer);
	}else{
		res.redirect('/login');
	}
}

/**
 * 支付宝页面跳转同步通知页面
 * 2017.01.04  by 胡斌
 */
exports.alipayReturnPage = function(req,res) {
	var data	= req.query;
	var sign	= data.sign;
	if(sign==mdAlipay.getSign(data)){
		if(data.trade_status=="TRADE_SUCCESS"){
			res.redirect('/user/bill?id='+data.out_trade_no);
		}else{
			res.redirect('/user/bill?id='+data.out_trade_no);
		}
	}else{
		next();
	}
}

/**
 * 服务器异步通知页面路径
 * 2017.01.04  by 胡斌
 */
exports.alipayNotifyPage = function(req,res) {
	console.log(req.body);
	console.log(req.query);
	res.send("success");
}



exports.articleDetailPage = function(req, res, next) {
	//console.dir(req.AV.user);
	var name	= decodeURI(req.query.name);

	var querySysConfig 	= new AV.Query(avSysConfig);
	querySysConfig.equalTo("name",name);
	querySysConfig.first().then(function(result){
		if(typeof(result)=="undefined"){
			var newSysConfig=new avSysConfig();
			newSysConfig.set("name",name);
			newSysConfig.set("type","article");
			newSysConfig.set("value","");
			return newSysConfig.save();
		}else{
			return AV.Promise.as(result);
		}
	}).then(function(result) {
		if(result){
			res.render('main/article.html',{
				user:req.AV.user,
				result:result,
				moment:moment
			});
		}else{
			next();
		}
	},function(error) {
		mdCommon.sentErr(res,req,error);
	});
}

exports.itemListPage = function(req, res) {
	var queryBrand 			= new AV.Query(avBrand);
	var querySysConfig 	= new AV.Query(avSysConfig);
	var sex							= req.query.sex;
	var keyword					= req.query.keyword;
	var type						= "new";
	if(sex=="婴儿")type	= "baby";
	if(sex=="男孩")type	= "boy";
	if(sex=="女孩")type	= "girl";
	//console.log(keyword);
	if(typeof(keyword)!="undefined")type	= false;
	//console.log(false);

	querySysConfig.equalTo("type","data");

	AV.Promise.when(
		querySysConfig.find(),
		queryBrand.find()
	).then(function(datas,brands){
		//console.log(datas);
		var data={};
		for(var i=0;i<datas.length;i++){
			data[datas[i].get("name")]=datas[i].get("value").split(',');
		}
		res.render('main/item-list.html',{
			user:req.AV.user,
			moment:moment,
			data:data,
			brands:brands,
			sex:sex,
			type:type,
			keyword:keyword
		});
	},function(error) {
		mdCommon.sentErr(res,req,error);
	});
}

exports.itemDetailPage = function(req, res) {
	//console.dir(req.AV.user);
	var id	= req.query.id;

	var querySysConfig 	= new AV.Query(avSysConfig);
	var queryItem 			= new AV.Query(avItem);

	querySysConfig.equalTo("name","物流配送");
	queryItem.equalTo("objectId",id);
	queryItem.equalTo("enabled",true);
	queryItem.include("Brand");
	AV.Promise.when(
		querySysConfig.first(),
		queryItem.first()
	).then(function(artcle,result) {
		if(result){
			res.render('main/item-detail.html',{
				user:req.AV.user,
				result:result,
				artcle:artcle,
				brand:result.get("Brand"),
				moment:moment
			});
		}else{
			next();
		}
	},function(error) {
		mdCommon.sentErr(res,req,error);
	});
}

exports.myCollectionsPage = function(req, res) {
	var user = req.AV.user;
	if(user){
		res.render('main/my-collections.html',{
			user:req.AV.user,
			moment:moment
		});
	}else{
		res.redirect('/login?refer=/user/collections');
	}
}

exports.myCollectionsPage = function(req, res) {
	var user = req.AV.user;
	if(user){
		res.render('main/my-collections.html',{
			user:req.AV.user,
			moment:moment
		});
	}else{
		res.redirect('/login?refer=/user/collections');
	}
}

exports.myBillPage = function(req, res) {
	var user = req.AV.user;
	if(user){
		var queryBrand 		= new AV.Query(avBrand);
		var query 				= new AV.Query(avCart);
		query.equalTo("user",user);
		query.notEqualTo("isPosted",true);
		query.include("item");
		AV.Promise.when(
			query.find(),
			queryBrand.find()
		).then(function(results,Brands) {
			var BrandArr = {};
			for(var i=0;i<Brands.length;i++){
				BrandArr[Brands[i].id]=Brands[i].get("name");
			}

			var CartArr=[];
			for(var i=0;i<results.length;i++){
				var item	= results[i].get('item');
				var stock	= item.get("stock");
				var index	= item.get("size").indexOf(results[i].get('size'));
				CartArr[i]={};
				CartArr[i].id			= results[i].id;
				CartArr[i].Brand	= BrandArr[item.get('Brand').id];
				CartArr[i].cover	= results[i].get('item').get('cover');
				CartArr[i].title	= results[i].get('item').get('title');
				CartArr[i].size		= results[i].get('size');
				CartArr[i].price	= item.get("price");
				CartArr[i].num		= results[i].get("num");
				if(index<0){
					CartArr[i].stock=0;
				}else{
					CartArr[i].stock=stock[index];
				}
			}
			res.render('main/my-cart.html',{
				user:req.AV.user,
				results:CartArr,
				Brands:BrandArr,
				moment:moment
			});
		},function(error) {
			mdCommon.sentErr(res,req,error);
		});
	}else{
		res.redirect('/login?refer=/user/cart');
	}
}

exports.myCartPage = function(req, res) {
	var user = req.AV.user;
	if(user){
		var queryBrand 		= new AV.Query(avBrand);
		var query 				= new AV.Query(avCart);
		query.equalTo("user",user);
		query.notEqualTo("isPosted",true);
		query.include("item");
		AV.Promise.when(
			query.find(),
			queryBrand.find()
		).then(function(results,Brands) {
			var BrandArr = {};
			for(var i=0;i<Brands.length;i++){
				BrandArr[Brands[i].id]=Brands[i].get("name");
			}

			var CartArr=[];
			for(var i=0;i<results.length;i++){
				var item	= results[i].get('item');
				var stock	= item.get("stock");
				var index	= item.get("size").indexOf(results[i].get('size'));
				CartArr[i]={};
				CartArr[i].id			= results[i].id;
				CartArr[i].Brand	= BrandArr[item.get('Brand').id];
				CartArr[i].cover	= results[i].get('item').get('cover');
				CartArr[i].title	= results[i].get('item').get('title');
				CartArr[i].size		= results[i].get('size');
				CartArr[i].price	= item.get("price");
				CartArr[i].num		= results[i].get("num");
				if(index<0){
					CartArr[i].stock=0;
				}else{
					CartArr[i].stock=stock[index];
				}
			}
			res.render('main/my-cart.html',{
				user:req.AV.user,
				results:CartArr,
				Brands:BrandArr,
				moment:moment
			});
		},function(error) {
			mdCommon.sentErr(res,req,error);
		});
	}else{
		res.redirect('/login?refer=/user/cart');
	}
}

exports.setAddressPage	= function(req, res) {
	var user = req.AV.user;
	if(user){
		var id			= req.query.id;
		var query 	= new AV.Query(avOrderList);
		query.equalTo("objectId",id);
		query.equalTo("user",user);
		query.first().then(function(result) {
			if(result){
				res.render('main/my-set-address.html',{
					user:req.AV.user,
					result:result,
					address:user.get('address'),
					moment:moment
				});
			}else{
				res.redirect('/login?refer=/user/cart');
			}
		},function(error) {
			mdCommon.sentErr(res,req,error);
		});
	}else{
		res.redirect('/login?refer=/user/cart');
	}
}

exports.brandListPage = function(req, res) {
	var queryBrand 			= new AV.Query(avBrand);

	queryBrand.ascending("name");
	queryBrand.find().then(function(brands){
		res.render('main/brand-list.html',{
			user:req.AV.user,
			brands:brands
		});
	},function(error) {
		mdCommon.sentErr(res,req,error);
	});
}

exports.brandDetailPage = function(req, res) {
	//console.dir(req.AV.user);
	var id	= req.query.id;

	var queryBrand 			= new AV.Query(avBrand);
	queryBrand.equalTo("objectId",id);
	queryBrand.first().then(function(result) {
		res.render('main/brand-detail.html',{
			user:req.AV.user,
			result:result,
			moment:moment
		});
	},function(error) {
		mdCommon.sentErr(res,req,error);
	});
}

exports.doGetItems = function(req, res) {
	var pager,BrandArr=[];
	var queryItem 			= new AV.Query(avItem);
	var size			= req.query.size;
	var brand			= req.query.brand;
	var type			= req.query.type;
	var isNew			= req.query.isNew;
	var sex				= req.query.sex;
	var keyword		= req.query.keyword;
	var maxprice	= parseInt(req.query.maxprice);
	var minprice	= parseInt(req.query.minprice);
	var orderby		= req.query.orderby;
	var ordertype	= req.query.ordertype;

	queryItem.equalTo("enabled",true);
	if(brand){
		var brandIdsArr	= brand.split(",");
		if(brandIdsArr.length>0){
			for(var i=0;i<brandIdsArr.length;i++){
				var Brand	= new avBrand();
				Brand.id	= brandIdsArr[i];
				BrandArr.push(Brand);
			}
			queryItem.containedIn("Brand",BrandArr);
		}
	}
	if(keyword)queryItem.contains('title',keyword);
	if(size)queryItem.containedIn("size",size.split(","));
	if(type)queryItem.containedIn("type",type.split(","));
	if(sex)queryItem.containedIn("sex",sex.split(","));
	if(isNew && isNew=="new")queryItem.notEqualTo("isNew",false);
	//console.log(isNew);
	//console.log(ordertype);
	if(!isNaN(maxprice))
	queryItem.lessThanOrEqualTo("price",maxprice);
	if(!isNaN(minprice))
	queryItem.greaterThanOrEqualTo("price",minprice);

	if(orderby!="price"){
		if(ordertype=="asc")
		queryItem.descending("createdAt");
		else
		queryItem.ascending("createdAt");
	}else{
		if(ordertype=="desc")
		queryItem.descending("price");
		else
		queryItem.ascending("price");
	}

	queryItem.count().then(function(count){
		//console.log(count);
		pager		= mdCommon.Paginate(req.query.page, req.query.pagesize, count);
		queryItem.limit(pager.pagesize);
		queryItem.skip(pager.pagesize*(pager.currentPage-1));
		queryItem.include("Brand");
		queryItem.select('Brand', 'cover', 'bcover', 'title', 'price');
		return queryItem.find();
	}).then(function(results){
		var items=[];
		for(var i=0;i<results.length;i++){
			items[i]={};
			items[i].id			= results[i].id;
			items[i].cover	= results[i].get("cover");
			items[i].bcover	= results[i].get("bcover");
			items[i].title	= results[i].get("title");
			items[i].price	= results[i].get("price");
			items[i].Brand	= results[i].get("Brand").get("name");
		}
		res.json({items:items,pager:pager});
	},function(error) {
		mdCommon.sentErr(res,req,error);
	});
}

exports.doAddCollections = function(req, res) {
	var user	= req.AV.user;
	var id		= req.body.id;
	if(user){
		user.addUnique('collections',id);
		user.save().then(function(result) {
			res.json({user:user});
		},function(error) {
			mdCommon.sentErr(res,req,error);
		});
	}else{
		res.json({user:false});
	}
}

exports.doGetCollections = function(req, res) {
	var pager;
	var user	= req.AV.user;
	var id		= req.body.id;
	if(user){
		var ids							= user.get('collections');
		var queryItem 			= new AV.Query(avItem);
		queryItem.containedIn("objectId",ids);
		queryItem.equalTo("enabled",true);
		queryItem.count().then(function(count){
			//console.log(count);
			pager		= mdCommon.Paginate(req.query.page, req.query.pagesize, count);
			queryItem.limit(pager.pagesize);
			queryItem.skip(pager.pagesize*(pager.currentPage-1));
			queryItem.include("Brand");
			queryItem.select('Brand', 'cover', 'bcover', 'title', 'price');
			return queryItem.find();
		}).then(function(results){
			var items=[];
			for(var i=0;i<results.length;i++){
				items[i]={};
				items[i].id			= results[i].id;
				items[i].cover	= results[i].get("cover");
				items[i].bcover	= results[i].get("bcover");
				items[i].title	= results[i].get("title");
				items[i].price	= results[i].get("price");
				items[i].Brand	= results[i].get("Brand").get("name");
			}
			res.json({items:items,pager:pager});
		},function(error) {
			mdCommon.sentErr(res,req,error);
		});
	}else{
		res.json({user:false});
	}
}

exports.doAddCart = function(req, res) {
	var user	= req.AV.user;
	var id		= req.body.id;
	var num		= parseInt(req.body.num);
	var size	= req.body.size;
//	console.log(id);
	if(user){
		var item	= new avItem();
		var cart	= new avCart();
		item.id	= id;
		cart.set("item",item);
		cart.set("size",size);
		cart.set("num",num);
		cart.set("user",user);
		cart.save().then(function(result){
			var query = new AV.Query(avCart);
			query.equalTo("user",user);
			return query.count();
		}).then(function(count){
			res.json({user:user,count:count});
		},function(error) {
			mdCommon.sentErr(res,req,error);
		});
	}else{
		res.json({user:false});
	}
}

exports.doDelCart = function(req, res) {
	var user	= req.AV.user;
	var ids		= req.body.ids;
	if(user){
		var query = new AV.Query(avCart);
		query.equalTo("user",user);
		query.containedIn("objectId",ids);
		query.find().then(function(results){
			return AV.Object.destroyAll(results);
		}).then(function(){
			res.json({success:true});
		},function(error) {
			mdCommon.sentErr(res,req,error);
		});
	}else{
		res.json({user:false});
	}
}

exports.doGetCartCount = function(req, res) {
	var user	= req.AV.user;
	if(user){
		var query = new AV.Query(avCart);
		query.equalTo("user",user);
		query.notEqualTo("isPosted",true);
		query.count().then(function(count){
			res.json({user:user,count:count});
		},function(error) {
			mdCommon.sentErr(res,req,error);
		});
	}else{
		res.json({user:false});
	}
}

exports.doCreateBill = function(req, res) {
	var user	= req.AV.user;
	if(user){
		var itemNums={};
		var itemArr	= req.body.items;
		var query 	= new AV.Query(avCart);
		var itemIds	= [];
		for(var i=0;i<itemArr.length;i++){
			itemIds.push(itemArr[i].id);
			itemNums[itemArr[i].id]=parseInt(itemArr[i].num);
		}
		//console.log(111);
		query.containedIn("objectId",itemIds);
		query.equalTo("user",user);
		query.include("item");
		query.find().then(function(results){
			var items			= [];
			var amount		= 0;
			var promises	= [];
			var cartArr		= [];
			var stockArr	= {};
			for(var i=0;i<results.length;i++){
				items[i]	= results[i].get("item");
				if(!stockArr[items[i].id]){
					stockArr[items[i].id]	= items[i].get("stock");
				}
				var size	= items[i].get("size");
				var index	= size.indexOf(results[i].get("size"));
				if(index>-1){
					console.log("index:"+index+" | stock[index]="+stockArr[items[i].id][index]);
					var num 	= parseInt(stockArr[items[i].id][index])-itemNums[results[i].id];
					if(num<0 || num==null || isNaN(num))num=0;
					stockArr[items[i].id][index]=num;
					items[i].set("stock",stockArr[items[i].id]);
					results[i].set("num",itemNums[results[i].id]);
					results[i].set("isPosted",true);
					results[i].set("price",items[i].get("price"));
					results[i].set("title",items[i].get("title"));
					results[i].set("detail",items[i].toJSON());
					cartArr.push(results[i].id);
					amount+=itemNums[results[i].id]*results[i].get("price");
					promises.push(items[i].save());
					promises.push(results[i].save());
				}
			}
			if(cartArr.length>0){
				var SN						= mdCommon.getSN();
				var	newOrderList	= new avOrderList();
				newOrderList.set("cartArr",cartArr);
				newOrderList.set("amount",amount);
				newOrderList.set("toBePaid",amount);
				newOrderList.set("user",user);
				newOrderList.set("SN",SN);
				promises.push(newOrderList.save());
				return AV.Promise.all(promises);
			}else{
				return AV.Promise.error("库存不足");
			}
		}).then(function(results){
			console.log(results.length);
			res.json({success:true,id:results[results.length-1].id});
		},function(error) {
			mdCommon.sentErr(res,req,error);
		});
	}else{
		res.json({user:false});
	}
}

exports.doGetWXQR = function(req, res) {
	var id		= req.query.id;
	var ips		= req.ip.split(':');
	var queryOrderList	= new AV.Query(avOrderList);
	if(!id)id="-1";
	queryOrderList.equalTo("objectId",id);
	queryOrderList.first().then(function(result){
		var OrderList	=	result;
		var builder 	= new xml2js.Builder();  // JSON->xml
		var data={},json={};

		json['appid']			= mdWX.appID;
		json['body']			= "BeniBaby订单支付："+result.get("SN");
		json['mch_id']		= mdWX.mch_id;
		json['total_fee']	= 1;
		json['trade_type']				= "NATIVE";
		json['nonce_str']					= result.id;
		json['notify_url']				= "http://www.benibaby.com/wx/pcb";
		json['out_trade_no']			= result.get("SN");
		json['spbill_create_ip']	= ips[ips.length-1];
		json['product_id']				= result.id;
		json['sign']							= mdWX.getSign(json);
		data['xml']								= json;

		//console.log(data);
		var xml	=  builder.buildObject(data);

		var options = {
			headers: {'Content-Type':'text/xml; charset=utf-8'},
			url: 'https://api.mch.weixin.qq.com/pay/unifiedorder',
			method: 'POST',
			body: xml
		}
		request.post(options,function (error, response, body) {
			//console.log(body);
			var parseString = xml2js.parseString;
			parseString(body,{explicitArray : false}, function(err, data) {
				//console.log("1");
				//console.log(err);
				if(data.xml.return_code=="FAIL"){
					console.error(data.xml.return_msg);
					res.redirect("/i/error.png");
				}else if(data.xml.err_code_des){
					console.error(data.xml.err_code_des);
					res.redirect("/i/error.png");
				}else{
					OrderList.set("wxPrepayId",data.xml.prepay_id);
					OrderList.set("wxPayData",data.xml);
					OrderList.save().then(function(result){
						var data	 = result.get("wxPayData");
						//console.log(data);
						var qrcode = qr.image(data.code_url);
					  res.type('png');
					  qrcode.pipe(res);
					},function(error) {
						res.redirect("/i/error.png");
					});
				}
			});
		});
	},function(error) {
		res.redirect("/i/error.png");
	});
}

exports.doAlipay = function(req, res) {
	var id		= req.query.id;
	var ips		= req.ip.split(':');
	var queryOrderList	= new AV.Query(avOrderList);
	//if(!id)id="-1";
	if(id)queryOrderList.equalTo("objectId",id);
	queryOrderList.first().then(function(result){
		var OrderList	=	result;
		var builder 	= new xml2js.Builder();  // JSON->xml
		var data={},json={};

		json["service"]					= mdAlipay.service;
		json["partner"]					= mdAlipay.partner;
		json["seller_id"]				= mdAlipay.seller_id;
		json["payment_type"]		= mdAlipay.payment_type;
		json["notify_url"]			= mdAlipay.notify_url;
		json["return_url"]			= mdAlipay.return_url;
		json["out_trade_no"]		= result.id;
		json["subject"]					= result.get("SN");
		json["total_fee"]				= 0.01;
		json["body"]						= "BeniBaby订单支付："+result.get("SN");
		json["_input_charset"]	= "utf-8";

		var param=[],arr=[];
		var url		= mdAlipay.alipay_gateway+"_input_charset=utf-8";

		for(key in json){
			param.push(key);
		}
		param.sort();
		param.push('sign');
		param.push('sign_type');
		json['sign']						= mdAlipay.getSign(json);
		json['sign_type']				= mdAlipay.sign_type;
		//url	+=  arr.join("&");
		//console.log(url);
		res.render('alipay.html',{
			url:url,
			data:json,
			param:param
		});
	},function(error) {
		mdCommon.sentErr(res,req,error);
	});
}

/*exports.doGetWXQR = function(req, res) {
	var id		= req.query.id;
	var ips		= req.ip.split(':');
	var queryOrderList	= new AV.Query(avOrderList);
	if(!id)id="-1";
	queryOrderList.equalTo("objectId",id);
	queryOrderList.first().then(function(result){
		result.set("ip",ips[ips.length-1]);
		return result.save();
	}).then(function(result){
		var json={};
		json.appid			= mdWX.appID;
		json.mch_id			= mdWX.mch_id;
		json.product_id	= result.id;
		json.time_stamp	= moment().format("X");
		json.nonce_str	= result.get("SN");
		var url="weixin://wxpay/bizpayurl?sign="+mdWX.getSign(json)
		+"&appid="+json.appid
		+"&mch_id="+json.mch_id
		+"&product_id="+json.product_id
		+"&time_stamp="+json.time_stamp
		+"&nonce_str="+json.nonce_str;
		//console.log(url);
		var qrcode = qr.image(url);
	  res.type('png');
	  qrcode.pipe(res);
	},function(error) {
		res.redirect("/i/error.png");
	});
}*/

/**
 * 网站首页
 * 2015.04.25  by 胡斌
 */
exports.image = function(req,res,next) {
	var path	= req.path.split("/");
	var id		= req.query.id;
	//console.log("id="+id);
	var queryImage=new AV.Query(avImage);
	queryImage.equalTo("objectId",id);
	queryImage.first(function(image){
		//console.dir(image);
		//console.log(typeof(image.get("file")));
		if(typeof(image)=="undefined" || image==null || typeof(image.get("file"))!="object"){
			if(req.query.w==800)
			res.redirect("/i/default2.png");
			else
			res.redirect("/i/default.png");
		}else{
			var file= image.get("file");
			var w		= req.query.w;
			var h		= req.query.h;
			if(w && h && w>0 && h>0){
				res.redirect(file.thumbnailURL(w,h));
			}else{
				res.redirect(file.url());
			}
		}
	});
}

exports.doLogin = function(req,res) {
	AV.User.logIn(req.body.username,req.body.password).then(function(user) {
			res.saveCurrentUser(user);
			//跳转到profile页面。
			if(req.body.refer)
			res.redirect(decodeURI(req.body.refer));
			else
			res.redirect('/');
	},function(error) {
		if(typeof(error)=="object"){error=error.message;}
		console.error(error);
		//登录失败，跳转到登录页面
		res.redirect('/login?error='+error+"&refer="+req.body.refer);
	});
}

exports.doRegister = function(req,res) {
	var name				= req.body.username;
	var pw1					= req.body.password;
	var pw2					= req.body.password2;
	if(pw1==pw2){
		var user = new AV.User();// 新建 AVUser 对象实例
	  user.set("username",name);// 设置用户名
	  user.set("password",pw1);// 设置密码
	  user.setEmail(req.body.email);
	  user.signUp().then(function (loginedUser) {
			res.saveCurrentUser(loginedUser);
			if(req.body.refer)
			res.redirect(decodeURI(req.query.refer));
			else
			res.redirect('/');
	  }, (function (error) {
			if(typeof(error)=="object"){error=error.message;}
			res.redirect('/register?error='+error+"&refer="+req.body.refer);
	  }));
	}else{
		res.redirect('/register?error=密码不一致!'+"&refer="+req.body.refer);
	}
}

exports.doCkAuth = function(req,res,next) {
	//console.log(req.AV.user);
	if(req.AV.user){// 判断用户是否已经登录
		res.saveCurrentUser(req.AV.user);
	}
	next();
}

/**
 * 静态页面
 * 2015.04.20  by 胡斌
 */
exports.htmlPage = function(req,res) {
	var path	= req.path.split("/");
	var fn		= path[path.length-1];
	var type	= fn.split(".");
	display(res,type[0],{res:res});
}
